package com.nginxmanager.comment;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018-01-02.
 */
public class HttpRequest {

    /**
           * 发起http get请求获取nginx欢迎网页源代码
           * @param requestUrl     String    请求地址
           * @return                 String    该地址返回的html字符串
           */
    public  int httpRequest(String requestUrl) {

        Map<String,List<String>> map=null;
        HttpURLConnection httpUrlConn = null;
        List<String> server=null;
        int type=0;
//        System.out.println("什么鬼"+requestUrl);
        try {
            // 建立get请求
            URL url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoInput(true);
            httpUrlConn.setRequestMethod("GET");
            // 获取响应头部
            map=httpUrlConn.getHeaderFields();
            server = map.get("Server");

            if (server == null) {
                System.out.println("服务器未启动!");
            }else {
                // 取出有用的范围
                Pattern p = Pattern.compile("(.*)(nginx)(.*)");
                Matcher m = p.matcher(server.toString());
                if (!m.matches()) {
                    type = 1;
                    System.out.println("服务器被占用!");
                    return type;
                }
                type=2;
                for (String values : server) {
                    System.out.println(values);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return type;
    }
}
